package com.lzg.okrx

import com.lzg.extend.JsonConvert
import com.lzg.okrx.adapter.SingleBody
import com.lzy.okgo.OkGo
import com.lzy.okgo.convert.StringConvert
import com.lzy.okgo.model.HttpHeaders
import com.lzy.okgo.model.HttpMethod
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.request.base.Request
import io.reactivex.Single
import java.lang.reflect.Type

object RxSingleHelper {

    fun <T> request(
        method: HttpMethod = HttpMethod.POST,
        url: String = "",
        isMultipart: Boolean = false,
        type: Type? = null,
        clazz: Class<T>? = null,
        params: HttpParams? = null,
        headers: HttpHeaders? = null
    ): Single<T> {
        val request: Request<T, out Request<*, *>> = when (method) {
            HttpMethod.GET -> OkGo.get(url)
            HttpMethod.POST ->
                OkGo.post<T>(url)
                    .isMultipart(isMultipart)
            HttpMethod.PUT ->
                OkGo.put<T>(url)
                    .isMultipart(isMultipart)
            HttpMethod.DELETE ->
                OkGo.delete<T>(url)
                    .isMultipart(isMultipart)
            HttpMethod.HEAD -> OkGo.head(url)
            HttpMethod.PATCH ->
                OkGo.patch<T>(url)
                    .isMultipart(isMultipart)
            HttpMethod.OPTIONS ->
                OkGo.options<T>(url)
                    .isMultipart(isMultipart)
            HttpMethod.TRACE -> OkGo.trace(url)
        }

        request.headers(headers)
        request.params(params)
        when {
            type != null -> request.converter(JsonConvert(type))
            clazz != null -> request.converter(JsonConvert(clazz))
            else -> request.converter(JsonConvert<T>())
        }
        return request.adapt(SingleBody())
    }

    fun requestString(
        method: HttpMethod = HttpMethod.POST,
        url: String = "",
        isMultipart: Boolean = false,
        params: HttpParams? = null,
        headers: HttpHeaders? = null
    ): Single<String> {
        val request: Request<String, out Request<*, *>> = when (method) {
            HttpMethod.GET -> OkGo.get(url)
            HttpMethod.POST ->
                OkGo.post<String>(url)
                    .isMultipart(isMultipart)
            HttpMethod.PUT ->
                OkGo.put<String>(url)
                    .isMultipart(isMultipart)
            HttpMethod.DELETE ->
                OkGo.delete<String>(url)
                    .isMultipart(isMultipart)
            HttpMethod.HEAD -> OkGo.head(url)
            HttpMethod.PATCH ->
                OkGo.patch<String>(url)
                    .isMultipart(isMultipart)
            HttpMethod.OPTIONS ->
                OkGo.options<String>(url)
                    .isMultipart(isMultipart)
            HttpMethod.TRACE -> OkGo.trace(url)
        }

        request.headers(headers)
        request.params(params)
        request.converter(StringConvert())
        return request.adapt(SingleBody())
    }

}